﻿using System;
using System.Collections.Generic;
using System.Linq;
using Fortune.Attributes.API;
using Fortune.POCO;
using Newtonsoft.Json;
using UnityEngine;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace Fortune.API
{
    /// <summary>
    /// 获取游戏内当前全部配方数据
    /// </summary>
    [RequestMapping("/proto/recipe/_realTime")]
    public class BaseService : WebSocketBehavior
    {
        /// <summary>
        /// 收到消息时的处理方法
        /// </summary>
        /// <param name="e">消息对象</param>
        protected override void OnMessage(MessageEventArgs e)
        {
            try
            {
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };
                Debug.Log($@"接到消息 {e.Data}");
                Console.Out.WriteLine($@"接到消息 {e.Data}");
                List<Dictionary<string, object>> list = loadData(LDB._recipes.dataArray);

                string result = JsonConvert.SerializeObject(Result<object>.success(ID, list), settings);
                Console.Out.WriteLine(result);
                Send(result);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }

        /// <summary>
        /// 打开连接时的处理方法
        /// </summary>
        protected override void OnOpen()
        {
            Debug.Log($@"已连接 {ID}, IP {Context.Host}");
        }

        private static List<Dictionary<string, object>> loadData(IEnumerable<RecipeProto> recipeProtos)
        {
            return recipeProtos.Select(recipeProto => new Dictionary<string, object>()
                {
                    {"Type", recipeProto.Type},
                    {"Handcraft", recipeProto.Handcraft},
                    {"Explicit", recipeProto.Explicit},
                    {"TimeSpend", recipeProto.TimeSpend},
                    {"Items", recipeProto.Items},
                    {"ItemCounts", recipeProto.ItemCounts},
                    {"Results", recipeProto.Results},
                    {"ResultCounts", recipeProto.ResultCounts},
                    {"GridIndex", recipeProto.GridIndex},
                    {"IconPath", recipeProto.IconPath},
                    {"index", recipeProto.index},
                    {"ID", recipeProto.ID},
                    {"SID", recipeProto.SID},
                    {"madeFromString", recipeProto.madeFromString}
                })
                .ToList();
        }
    }
}